import { HttpClient } from '@angular/common/http';
import { ChangeDetectorRef, Component, DestroyRef, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';

import { CardInfo } from '@app/core/services/http/card-info/card-info.service';
import { CardRegex, CardRegexService } from '@app/core/services/http/card-regex/card-regex.service';
import { OperationService } from '@app/core/services/http/operation/operation.service';
import { SharedModule } from '@app/shared/shared.module';
import { BasicConfirmModalComponent } from '@app/widget/base-modal';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NZ_MODAL_DATA, NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-match-result-modal',
  standalone: true,
  imports: [SharedModule],
  templateUrl: './match-result-modal.component.html',
  styleUrls: ['./match-result-modal.component.less']
})
export class MatchResultModalComponent extends BasicConfirmModalComponent implements OnInit {
  isSpinningAdd: boolean = false;
  isEdit!: boolean;
  validateForm!: FormGroup;
  validationResult: string = '';
  readonly nzModalData: CardInfo[] = inject(NZ_MODAL_DATA);
  private readonly fb: FormBuilder = inject(FormBuilder);
  private readonly destroyRef: DestroyRef = inject(DestroyRef);
  private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef);
  private readonly messageService: NzMessageService = inject(NzMessageService);
  private readonly cardRegexService: CardRegexService = inject(CardRegexService);
  private readonly operationService: OperationService = inject(OperationService);

  constructor(
    override modalRef: NzModalRef,
    private readonly http: HttpClient
  ) {
    super(modalRef);
  }

  protected getCurrentValue(): Observable<NzSafeAny> {
    if (!this.validateForm.valid) {
      return of(false);
    }
    return of({ ...this.validateForm.value });
  }
  verify(item: CardInfo): void {
    let formData = new FormData();
    formData.set('title', item.cardnumber);
    formData.set('password', item.cardpassword);
    formData.set('submit', '立即查询');
    this.operationService
      .validate(item.cardnumber, item.cardpassword)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(res => {
        this.messageService.info(res);
      });
  }

  copyToClipboard(item: CardInfo): void {
    const text = `卡号: ${item.cardnumber}, 卡密: ${item.cardpassword}`;
    navigator.clipboard
      .writeText(text)
      .then(() => {
        this.messageService.success('复制成功');
      })
      .catch(err => {
        this.messageService.error('复制失败');
      });
  }

  ngOnInit(): void {
    this.isEdit = !!this.nzModalData;
  }
}
